/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import event.JobConfirmEvent;
import event.JobRequestEvent;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Direction;
import net.sf.appia.core.Event;
import net.sf.appia.core.Layer;
import net.sf.appia.core.Session;
import net.sf.appia.core.events.channel.ChannelInit;
import util.Erro;
import util.Info;

/**
 *
 * @author Welington
 */
public class JobSession extends Session {

    private Class current = JobSession.class;

    public JobSession(Layer layer) {
        super(layer);
    }

    @Override
    public void handle(Event event) {
        if (event instanceof ChannelInit) {
            handleChannelInit((ChannelInit) event);
        } else if (event instanceof JobRequestEvent) {
            handlePrintRequest((JobRequestEvent) event);
        }
    }

    private void handleChannelInit(ChannelInit init) {
        try {
            init.go();
        } catch (AppiaEventException e) {
            Erro.showMessage(current, e);
        }
    }

    private void handlePrintRequest(JobRequestEvent request) {
        try {
            JobConfirmEvent ack = new JobConfirmEvent();

            Info.showMessage(current, "Executing job {" + request.getString() + "}");
            request.go();

            ack.setChannel(request.getChannel()); // set the Appia channel where the
            // event will travel
            ack.setDir(Direction.UP); // set events direction
            ack.setSourceSession(this); // set the session that created the event
            ack.setId(request.getId()); // set the request ID
            // initializes the event, defining all internal structures,
            // for instance the path the event will take (sessions to visit)
            ack.init();
            ack.go(); // send the event
        } catch (AppiaEventException e) {
            Erro.showMessage(current, e);
        }
    }
}
